﻿using CPPEI.ETL.DataServiceInterface;
using CPPEI.ETL.Infrastructure;
using CPPEI.ETL.Infrastructure.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;

namespace CPPEI.ETL.DSImplement
{
    public class ExcelDtSerProxy : IDataServiceProxy
    {
        public TDataService GetSchema(DataServiceInfo info)
        {
            return null;
        }

        public TDataSource GetSchema(DataSourceInfo info)
        {
            return null;
        }

        public IData GetData(DataSourceInfo info, Dictionary<string, object> args)
        {
            FileInfo fileInfo = null;
            string sheetName = null;
            foreach (var key in args.Keys)
            {
                object argValue = args[key];
                if (argValue is FileInfo)
                {
                    fileInfo = argValue as FileInfo;
                }
                else
                {
                    if (argValue != null)
                    {
                        sheetName = argValue.ToString();
                    }
                }
            }

            bool firstRowAsHeader = false;
            if(!string.IsNullOrEmpty(info.Settings))
            {
                string[] segArr = info.Settings.Split(new char[] { ',' });
                for (int index = 0; index < segArr.Length; index++)
                {
                    string[] kvArr = segArr[index].Split(new char[] { '=' });
                    if(kvArr.Length >= 2)
                    {
                        if(string.Equals(kvArr[0], "FirstRowAsHeader"))
                        {
                            if(kvArr[1] == bool.FalseString)
                            {
                                firstRowAsHeader = false;
                            }
                            else
                            {
                                firstRowAsHeader = true;
                            }
                            break;
                        }
                    }
                }
            }

            // 读取数据
            DataTable dataTable = OpenXmlTool.ReadExcel(fileInfo.FullName, sheetName, firstRowAsHeader);

            return new DataTableData(dataTable);
        }

        public List<string> Enumerate(DataServiceInterface.DataServiceInfo info)
        {
            return null;
        }
    }
}
